package com.fancy.mobileschool.notify;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;


import com.fancy.mobileschool.MyConfiguration;
import com.fancy.mobileschool.entity.Course;
import com.fancy.mobileschool.service.CourseService;
import com.fancy.mobileschool.task.TaskExecutor;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.List;
import java.util.concurrent.Semaphore;

/**
 * Created by Jackie on 2017/11/23.
 *
 */

public class AttendNotify extends Service {

    private GetDataCallback callback;

    private IBinder binder = new MsgBinder();

    private List<Course> myCourse;

    private CourseService courseService = new CourseService();

    private Semaphore semaphore = new Semaphore(0);

    public static final String HOST = "tcp://120.78.197.155:61613";

    public static final String TOPIC = "course/attend/";

    private static final String clientid = MyConfiguration.myID;

    private MqttClient client;

    protected MqttConnectOptions options;

    public void setCallback(GetDataCallback callback) {
        this.callback = callback;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        TaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                myCourse = courseService.getMyGroupsForStudent(MyConfiguration.myID);
                semaphore.release();
            }
        });
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    public void listenerNotify() {
        connect();
        start();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        disconnect();
    }

    public interface GetDataCallback{

        void getData(String data);
    }

    public class MsgBinder extends Binder {

        public AttendNotify getService() {
            return AttendNotify.this;
        }

    }


    private void start() {
        try {

            semaphore.acquire();
            String[] topics = new String[myCourse.size()];
            semaphore.release();

            int[] Qos  = new int[myCourse.size()];
            for (int i = 0 ; i < Qos.length; i++) {
                Qos[i] = 1;
                topics[i] = TOPIC + myCourse.get(i).course_id;
            }

            client.subscribe(topics, Qos);
            client.setCallback(new DataCallback());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void disconnect() {
        try {
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    private void connect() {
        try {
            client = new MqttClient(HOST, clientid, new MemoryPersistence());
            options = new MqttConnectOptions();
            options.setCleanSession(true);
            String userName = "admin";
            options.setUserName(userName);
            String passWord = "password";
            options.setPassword(passWord.toCharArray());
            options.setConnectionTimeout(10);
            options.setKeepAliveInterval(20);
            options.setAutomaticReconnect(true);

            client.connect(options);
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }

    private class DataCallback implements MqttCallback {

        @Override
        public void connectionLost(Throwable cause) {
            cause.printStackTrace();
            //connect();
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            callback.getData(message.toString());
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    }

}
